package com.hmkj.web.controller.index;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.AliyunCodeKey;
import com.hmkj.core.constant.PhoneCodeKey;
import com.hmkj.core.constant.SessionId;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.userFreeze.UserFreeze;
import com.hmkj.core.service.user.UserService;
import com.hmkj.core.service.userFreeze.UserFreezeService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户登录
 *
 * @author Administrator
 */
@Api(description = "用户登录相关")
@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL)
public class AppLoginController extends GenericController<Integer, User> {


    @Resource
    private UserService userService;
    @Resource
    private UserFreezeService userFreezeService;

//    @ApiOperation(value = "缓存测试用户", notes = "缓存测试用户")
//    @ResponseBody
//    @RequestMapping(value = "pushTestUser", method = RequestMethod.POST)
//    public ResultEntity pushTestUser(HttpServletRequest request) {
//        User user1 = userService.selectByPrimaryKey(1);
//        sessionService.setSession(SessionId.MEMBER_USER, user1,request);
//        return ok();
//    }

    @ApiOperation(value = "登录/注册校验手机号", notes = "登录/注册校验手机号")
    @RequestMapping(value = "/checkPhone", method = RequestMethod.POST)
    public ResultEntity checkPhone(@ApiParam("手机号") @RequestParam String mobile) {
        //默认不存在
        Integer isExists = 1;
        if (StringUtils.isNotBlank(mobile) && null != userService.selectByMobile(mobile)) {
            isExists = 2;
        }
        return ok(isExists);
    }

    @ApiOperation(value = "用户登录", notes = "用户登录,rsa公钥:<br/>-----BEGIN PUBLIC KEY-----<br/>" +
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChMRzbRbNqutRD8DEa52AJP+ee<br/>" +
            "nq+hiOKMjAHZtyb50HCypTqyJoJBoZ8doLBoH84D/XUsLEafqMFwicl4JOmNc/Ui<br/>" +
            "x+Glq6lsVpvTo7foIpx6+yuujp8yoLIFixPwq3WHZAHUIeCmJx8JoRjDeNJVMrnP<br/>" +
            "0HrHIZRM2ADEN8mE7QIDAQAB<br/>" +
            "-----END PUBLIC KEY-----")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultEntity login(@ApiParam("手机号") @RequestParam String userName,
                              @ApiParam("密码(rsa加密再base64加密)") @RequestParam String password,
//                              @ApiParam("cid") @RequestParam String cid,
//                              @ApiParam("图片验证码") @RequestParam(required = true) String captcha,
                              HttpServletRequest request) {
        log.info("web用户登录");
        //检验图片验证码
//        checkCaptcha(captcha, cid);
        UserModel userModel = new UserModel(u -> {
            u.setPassword(password);
            u.setMobilePhone(userName);
            u.setLastLoginIp(getRequestIp(request));
        });

        // 校验用户名是否存在
        final User user = userService.selectOne(new User(u -> u.setMobilePhone(userModel.getMobilePhone())));
        if (user == null || user.getId() == null) {
            throw new BussinessException("用户名不存在");
        }
        //校验用户登录是否冻结
        UserFreeze userFreeze = userFreezeService.selectOne(new UserFreeze(f -> {
            f.setDelFlag(UserFreeze.DELFLAG.NORMAL.code);
            f.setUserId(user.getId());
        }));
        if (null == userFreeze || UserFreeze.FREEZINGLOGIN.T1.code != userFreeze.getFreezingLogin()) {
            throw new BussinessException("您的账号被冻结，请联系客服！");
        }
        // 校验用户名密码
        if (!UserModel.encodePwd(userModel.decryptPwd()).equals(user.getPassword())) {
            throw new BussinessException("密码错误,请重试");
        }
        userService.doLogin(userModel, request);
        return ok(m -> m.put("id", user.getId()));
    }

//    @ApiOperation(value = "短信登录", notes = "短信登录")
//    @RequestMapping(value = "/msgLogin", method = RequestMethod.POST)
//    public ResultEntity msgLogin(@ApiParam("手机号") @RequestParam String userName,
//                                 @ApiParam("短信") @RequestParam String code,
//                                 HttpServletRequest request) {
//        log.info("短信登录");
//        checkUserPhoneCode(userName, code, PhoneCodeKey.MSG_LOGIN);
//        UserModel userModel = new UserModel(u -> {
//            u.setMobilePhone(userName);
//            u.setLastLoginIp(getRequestIp(request));
//        });
//        // 校验用户名是否存在
//        final User user = userService.selectOne(new User(u -> u.setMobilePhone(userModel.getMobilePhone())));
//        if (user == null || user.getId() == null) {
//            throw new BussinessException("用户名不存在");
//        }
//
//        userService.doLogin(userModel, request);
//        return ok(m -> m.put("id", user.getId()));
//    }

//        userService.doLogin(userModel, request);
//        return ok(m -> m.put("id", user.getId()));
//    }

    @ApiOperation(value = "短信登录-发送短信", notes = "短信登录-发送短信")
    @RequestMapping(value = "msgLogin/send", method = RequestMethod.POST)
    public ResultEntity msgLoginSend(@ApiParam("手机号") @RequestParam final String userName,
                                     @ApiParam("cid") @RequestParam String cid,
                                     @ApiParam("图片验证码") @RequestParam String captcha) throws Exception {
        //检验图片验证码
        checkCaptcha(captcha, cid);
        int i = userService.selectCount(new User(u -> u.setMobilePhone(userName)));
        if (i != 1) {
            throw new BussinessException("未注册用户");
        }
        sendSmsCode(PhoneCodeKey.MSG_LOGIN, userName);
        return ok("发送短信成功", ResultEntity.SUCCESS);
    }
//    @ApiOperation(value = "短信登录-发送短信", notes = "短信登录-发送短信")
//    @RequestMapping(value = "msgLogin/send", method = RequestMethod.POST)
//    public ResultEntity msgLoginSend(@ApiParam("手机号") @RequestParam final String userName,
//                                     @ApiParam("cid") @RequestParam String cid,
//                                     @ApiParam("图片验证码") @RequestParam String captcha) throws Exception {
//        //检验图片验证码
//        checkCaptcha(captcha, cid);
//        int i = userService.selectCount(new User(u -> u.setMobilePhone(userName)));
//        if (i != 1) {
//            throw new BussinessException("未注册用户");
//        }
//        sendSmsCode(PhoneCodeKey.MSG_LOGIN, userName);
//        return ok("发送短信成功");
//    }

    @ApiOperation(value = "用户登出", notes = "用户登出")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ResultEntity logout(HttpServletRequest request) {
        log.info("web用户登出");
        String hid = request.getParameter(SessionId.COOKIE_SESSIONID);
        redisService.del("SESSION:" + hid);
        // 登录动作
        return ok("退出成功", ResultEntity.SUCCESS);
    }

    @ApiOperation(value = "找回密码1", notes = "找回密码1")
    @RequestMapping(value = "codetopwd", method = RequestMethod.POST)
    public ResultEntity getCodeToPwd(@ApiParam("手机号") @RequestParam String mobile,
                                     @ApiParam("手机验证码") @RequestParam String captcha) throws Exception {
        log.info("忘记密码校验手机验证码");
        final Integer i = userService.selectCount(new User(u -> u.setMobilePhone(mobile)));
        if (i != 1) throw new BussinessException("当前用户不存在");
        checkUserPhoneCode(mobile, captcha, PhoneCodeKey.RESET_PWD);
        return ok("找回密码成功", ResultEntity.SUCCESS);
    }

    @ApiOperation(value = "找回密码2", notes = "找回密码2")
    @RequestMapping(value = "editPwd", method = RequestMethod.POST)
    public ResultEntity editPwd(@ApiParam("手机号") @RequestParam String mobile,
                                @ApiParam("cid") @RequestParam String cid,
                                @ApiParam("图片验证码") @RequestParam String captcha,
                                @ApiParam("验证码") @RequestParam String code,
                                @ApiParam("密码") @RequestParam String password) throws Exception {
        log.info("忘记密码修改密码");
        //检验图片验证码
        checkCaptcha(captcha, cid);
        checkUserPhoneCode(mobile, code, PhoneCodeKey.RESET_PWD);
        User user = userService.selectOne(new User(u -> {
            u.setMobilePhone(mobile);
            u.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if (null == user) {
            throw new BussinessException("该手机暂未注册用户");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(user.getId());
            u.setPassword(UserModel.staticEncodePwd(UserModel.staticDecryptPwd(password)));
        }));
        return ok("找回密码成功", ResultEntity.SUCCESS);
    }

    @ApiOperation(value = "找回密码-发送短信", notes = "找回密码-发送短信")
    @RequestMapping(value = "sendCode", method = RequestMethod.POST)
    public ResultEntity sendCode(@ApiParam("手机号") @RequestParam String mobile,
                                 @ApiParam("cid") @RequestParam String cid,
                                 @ApiParam("图片验证码") @RequestParam String captcha) throws Exception {
        log.info("忘记密码修改密码");
        //检验图片验证码
        checkCaptcha(captcha, cid);
        User user = userService.selectOne(new User(u -> {
            u.setMobilePhone(mobile);
            u.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if (null == user) {
            throw new BussinessException("该手机暂未注册用户");
        }
        sendSmsCode(AliyunCodeKey.RESET_PWD, "找回密码", mobile);
        return ok("找回密码-发送短信成功", ResultEntity.SUCCESS);
    }

}
